package com.test.demo

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewTreeObserver
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.test.demo.base.BaseActivity
import com.test.demo.databinding.ActivityMainBinding
import com.test.demo.main.activity.FeedDetailsActivity
import com.test.demo.main.adapter.FeedListAdapter
import com.test.demo.main.data.MainViewModel

/**
 * @description 主页面
 *
 */
class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>() {
    override fun layoutId(): Int {
        return R.layout.activity_main
    }

    override fun initView(savedInstanceState: Bundle?) {

        var adapter = FeedListAdapter()
        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        adapter.setOnItemClickListener(object : OnItemClickListener {
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                //动态详情
                var intent =
                    Intent(this@MainActivity, FeedDetailsActivity::class.java)
                startActivity(intent)
            }
        })


        setTextView()
    }

    private fun setTextView() {
        binding.tvConetnt.maxLines = 3
        binding.tvConetnt.viewTreeObserver.addOnPreDrawListener(object :
            ViewTreeObserver.OnPreDrawListener {
            override fun onPreDraw(): Boolean {
                // 获取 TextView 的行数
                val lineCount: Int = binding.tvConetnt.getLineCount()
                // 如果行数大于指定的最大行数，显示展开按钮，否则隐藏
                binding.tvUnfold.visibility = if (lineCount > 3) View.VISIBLE else View.GONE
                if (lineCount > 3) {
                    binding.tvConetnt.maxLines = 3
                    binding.tvConetnt.ellipsize = TextUtils.TruncateAt.END
                }
                // 移除监听，避免多次触发
                binding.tvConetnt.viewTreeObserver.removeOnPreDrawListener(this)
                return true
            }
        })
        binding.tvUnfold.setOnClickListener {
            // 切换 TextView 的最大行数，实现展开和收起效果
            binding.tvConetnt.maxLines = if (binding.tvConetnt.maxLines == 3) Int.MAX_VALUE else 3
            // 更新按钮文本
            binding.tvUnfold.text = if (binding.tvConetnt.maxLines == 3) "展开" else "收起"
        }
    }


}